package com.ryan.demo.xstream.utils.xml;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.ryan.demo.myio.utils.FileReader;
import com.ryan.demo.xstream.model.json.Birthday;
import com.ryan.demo.xstream.model.json.ListBean;
import com.ryan.demo.xstream.model.json.Student;
import com.ryan.demo.xstream.model.xstream.CpsResponse;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * <b>function:</b>Java对象和XML字符串的相互转换
 * jar-lib-version: xstream-1.3.1
 * 通过XStream对象的toXML方法就可以完成Java对象到XML的转换，
 * toXML方法还有2个相同签名的方法，
 * 需要传递一个流。然后通过流来完成xml信息的输出。
 * @author Ryan.Guo
 * @createDate Nov 27, 2010 12:15:15 PM
 * @file XStreamParser
 * @package com.ryan.demo.xstream
 * @project ryanTest
 * @blog 
 * @email ryan.guo2008@gmail.com
 * @version 1.0
 */
public class XmlParser {

	/**
	 * 请求XML->TO映射器
	 */
	private static final XStream xstream = new XStream(new DomDriver()); 
	
	static{
		xstream.processAnnotations(new Class<?>[]{CpsResponse.class});		
	}
	
    private ObjectOutputStream  out = null;
    private ObjectInputStream in = null;
    
    private Student bean = null;

    
    public XmlParser(){
    	init();
    }
    
    /**
     * <b>function:</b>初始化资源准备
     * @author hoojo
     * @createDate Nov 27, 2010 12:16:28 PM
     */
    public void init() {
        bean = new Student();
        bean.setAddress("china");
        bean.setEmail("jack@email.com");
        bean.setId(1);
        bean.setName("jack");
        Birthday day = new Birthday();
        day.setBirthday("2010-11-22");
        bean.setBirthday(day);
    }
    
    /**
     * <b>function:</b>释放对象资源
     * @author hoojo
     * @createDate Nov 27, 2010 12:16:38 PM
     */
    public void destory() {
        bean = null;
        try {
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.gc();
    }
    /**
     * <b>function:</b>Java对象转换成XML字符串
     * 看结果中的第一份xml内容，是没有经过然后修改或重命名的文档，
     * 按照原样输出。文档中的第二份文档的package经过重命名，
     * email属性也经过重命名以及类名也可以进行重命名的。
     * @author hoojo
     * @createDate Nov 27, 2010 12:19:01 PM
     */
    public void writeBean2XML() {
        try {
            System.out.println("------------Bean->XML------------");
            System.out.println(xstream.toXML(bean));
            System.out.println("重命名后的XML");
            //类重命名
            //xstream.alias("account", Student.class);
            //xstream.alias("生日", Birthday.class);
            //xstream.aliasField("生日", Student.class, "birthday");
            //xstream.aliasField("生日", Birthday.class, "birthday");
            //System.out.println(xstream.toXML(bean));
            //属性重命名
            xstream.aliasField("邮件", Student.class, "email");
            //包重命名
            xstream.aliasPackage("hoo", "com.hoo.entity");
            System.out.println(xstream.toXML(bean));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * <b>function:</b>将Java的List集合转换成XML对象
     * @author hoojo
     * @createDate Nov 27, 2010 12:20:07 PM
     */
    public String writeList2XML() {
        ListBean listBean = new ListBean();
        try {
            //修改元素名称
            xstream.alias("beans", ListBean.class);
            xstream.alias("student", Student.class);
            System.out.println("----------List-->XML----------");
            listBean.setName("this is a List Collection");
            
            List<Object> list = new ArrayList<Object>();
            list.add(bean);
            list.add(bean);//引用bean
            //list.add(listBean);//引用listBean，父元素
            
            bean = new Student();
            bean.setAddress("china");
            bean.setEmail("tom@125.com");
            bean.setId(2);
            bean.setName("tom");
            Birthday day = new Birthday("2010-11-22");
            bean.setBirthday(day);

            list.add(bean);
            list.add(bean);
            listBean.setList(list);
            
            //将ListBean中的集合设置空元素，即不显示集合元素标签
            //xstream.addImplicitCollection(ListBean.class, "list");
            
            //设置reference模型
            //xstream.setMode(XStream.NO_REFERENCES);//不引用
            xstream.setMode(XStream.ID_REFERENCES);//id引用
            //xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);//绝对路径引用
              
            //将name设置为父类（Student）的元素的属性
            xstream.useAttributeFor(Student.class, "name");
            xstream.useAttributeFor(Birthday.class, "birthday");
            //修改属性的name
            xstream.aliasAttribute("姓名", "name");
            xstream.aliasField("生日", Birthday.class, "birthday");
          
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(xstream.toXML(listBean));
        return xstream.toXML(listBean);
    }
    
	public Object xmlToBean(){
		try {
			String fis = FileReader.readFile("classpath:xstream/config.xml");
			return xstream.fromXML(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

    
}
